import React, { Component } from 'react'
import './data-process.css';
import { Row, Col, Input, message, Tabs, InputNumber, DatePicker, LocaleProvider } from 'antd';
import zh_CN from 'antd/lib/locale-provider/zh_CN';  // 将日期选择器设置为中文
import moment from 'moment';
import 'moment/locale/zh-cn';  // 将日期选择器设置为中文

import DataConfig from '../../components/data-config/data-config.jsx';
import GlobalDataConfig from '../../components/data-config/global-data-config';
import MbMgt from '../../components/data-config/mb-mgt';
//import DataProcessContent from './data-process-content';
import DaoDemo from '../../components/dragDemo/daoDemo';
import { connect } from 'react-redux';
import { editDataDocHeaderInfo, initDaosDataList, initdocData, initmbData, isCancleSelected, setDocInReducer, replaceNewCurves, setEditDepthData } from '../../redux/actions';
import { removeDocDataList, removeDepthData, } from '../../utils/storageUtils';
import { reqDocDataByBiaotou } from '../../api';
import html2canvas from 'html2canvas';
import downIcon from '../../assets/image/down.png'
const { TabPane } = Tabs;
const dateFormat = 'YYYY-MM-DD';
moment.locale('zh-cn');   // 将日期选择器设置为中文  

class DataProcess extends Component {

  constructor(props) {
    super(props);
    this.state = {
      subkey: '',
      isFixed: false,
      scrollLeft: 0,

      temp_val: 0,
      temp_name: '',

      open_angle: 0,
      start_depth: 0,
      end_depth: 0,
      open_position: 0, //开孔方向
      declination: 0, //磁偏角
      prospect_line_position: 0,  //勘探线方位（度）

      open_angle_1: 0,
      start_depth_1: 0,
      end_depth_1: 0,
      open_position_1: 0, //开孔方向
      declination_1: 0, //磁偏角
      prospect_line_position_1: 0,  //勘探线方位（度）
      showHeaderState: true
    }
  };

  handleOnChange = (e, name) => {
    const data = {
      info_name: name,
      info_value: e.target.value
    }
    this.props.editDataDocHeaderInfo(data);
  }

  handleOnChange1 = (value, name) => {
    // const { value } = e.target;

    // if ( value.length < 7 || value === '') {   // 如果是数字
    // const data = {
    //   info_name: name,
    //   info_value: value
    // }

    let val_name = ""
    switch (name) {
      case "开孔倾角": val_name = 'open_angle_1'; break;
      case "开孔方位": val_name = 'open_position_1'; break;
      case "起始深度": val_name = 'start_depth_1'; break;
      case "磁偏角": val_name = 'declination_1'; break;
      case "终止深度": val_name = 'end_depth_1'; break;
      case "勘探线方位": val_name = 'prospect_line_position_1'; break;
      default: val_name = '';
    }
    this.setState({
      temp_val: value,
      temp_name: name,
      [val_name]: value
    })
  }
  // }

  handleOnChange2 = (e, dateString, name) => {
    //console.log("更改后的input值2",e,dateString,name);
    const data = {
      info_name: name,
      info_value: dateString
    }
    this.props.editDataDocHeaderInfo(data);
    //console.log("数字input", this.props.docData);
  }

  handleOnPressEnter = async (e) => {    // 表头输入框enter键时，实时更新曲线
    // console.log(e)
    // 将文件发给后端，重新计算
    var docData_old = JSON.parse(JSON.stringify(this.props.docData));

    //如果是绘图文件就把内层的docData拿出来处理
    if (docData_old.docData) {
      docData_old = docData_old.docData;
    }
    var result;
    if (docData_old.doc_type === "纯数据文件") {
      docData_old.curves.map((item, index) => {
        if (item.type === 'yx') {
          docData_old.curves.splice(index, 1);  // 将curves中的岩性曲线删除;
        }
      });
      docData_old.open_angle = this.state.open_angle_1;
      docData_old.start_depth = this.state.start_depth_1;
      docData_old.end_depth = this.state.end_depth_1;
      docData_old.open_position = this.state.open_position_1;
      docData_old.declination = this.state.declination_1;
      docData_old.prospect_line_position = this.state.prospect_line_position_1;
      console.log("表头被修改，更新", this.state.start_depth_1, docData_old);
      result = await reqDocDataByBiaotou(docData_old);
      // console.log("表头重新计算结果",result);


      if (result.code === 200) {

        var docData = JSON.parse(JSON.stringify(result.data));
        if (docData.rock_curve) {
          docData.curves.push(docData.rock_curve);    // 将岩性曲线 推入 曲线数组中
        }
        this.props.setDocInReducer(docData);  // 更新 docData
        this.props.setEditDepthData(Number(docData.start_depth), Number(docData.end_depth), Number(docData.interval)); // 更新深度轴
        this.props.replaceNewCurves(docData.curves);   // 更新 daosDataList  

        //更新state
        console.log("--------修改数据成功")
        console.log(result.data)
        this.setState({
          open_angle: result.data.open_angle,
          start_depth: result.data.start_depth,
          end_depth: result.data.end_depth,
          open_position: result.data.open_position,
          declination: result.data.declination,
          prospect_line_position: result.data.prospect_line_position,
        })

        const data = {
          info_name: this.state.temp_name,
          info_value: this.state.temp_val
        }

        this.props.editDataDocHeaderInfo(data);


      } else if (result.code === 400) {
        message.info("输入超出深度范围！");
        this.setState({
          open_angle_1: this.state.open_angle,
          start_depth_1: this.state.start_depth,
          end_depth_1: this.state.end_depth,
          open_position_1: this.state.open_position,
          declination_1: this.state.declination,
          prospect_line_position_1: this.state.prospect_line_position,
        })

      } else {
        alert("请求失败！");
      }
    } else if (docData_old.doc_type === "绘图文件") {
      docData_old.docData.curves.map((item, index) => {
        if (item.type === 'yx') {
          docData_old.docData.curves.splice(index, 1);   // 将curves中的岩性曲线删除
        }
      });
      console.log("表头被修改，更新", docData_old);
      result = await reqDocDataByBiaotou(docData_old.docData);
      console.log("表头重新计算结果", result);
      if (result.code === 200) {
        var docData = JSON.parse(JSON.stringify(result.data));
        if (docData.rock_curve) {
          docData.curves.push(docData.rock_curve);    // 将岩性曲线 推入 曲线数组中
        }
        var drawDocData = JSON.parse(JSON.stringify(this.props.docData));
        drawDocData.docData = docData;   // 将修改后的 数据文件 插入到 绘图文件中
        this.props.setDocInReducer(drawDocData);  // 更新 docData
        this.props.setEditDepthData(Number(docData.start_depth), Number(docData.end_depth), Number(docData.interval));  //更新深度轴
        this.props.replaceNewCurves(docData.curves);   // 更新 daosDataList 
      } else if (result.code === 400) {
        alert("超出深度范围！");
      } else {
        alert("请求失败！");
      }
    }
  }


  handlesaveDocPic = async () => {    // 另存为图片
    const newCanvas = document.createElement("canvas");
    const element = document.querySelector('.data-process-content');

    // 获取 导出图片的 width和height
    const dom_width = parseInt(this._container.scrollWidth)            //parseInt(window.getComputedStyle(element).width);
    const dom_height = parseInt(this._container.scrollHeight)           //parseInt(window.getComputedStyle(element).height);
    console.log(dom_width);
    console.log(dom_height);


    //将canvas画布放大若干倍，然后盛放在较小的容器内，就显得不模糊了
    newCanvas.width = dom_width * 2;
    newCanvas.height = dom_height * 2;
    // newCanvas.style.width = dom_width + "px";
    // newCanvas.style.height = dom_height + "px";
    const context = newCanvas.getContext("2d");
    context.scale(1.8, 1.8);

    console.log(newCanvas)
    html2canvas(element, {
      canvas: newCanvas,
      allowTaint: false,
      logging: false,
      useCORS: true,
      backgroundColor: null
    }).then((canvas) => {  // 截取范围是 element这个div中的内容
      const imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
      const base64ToBlob = (code) => {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);  // let raw = window.atob(parts[1]);
        let rawLength = raw.length;

        let uInt8Array = new Uint8Array(rawLength);

        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], { type: contentType });
      };
      const blob = base64ToBlob(imgUri);
      // window.location.href = imgUri; // 下载图片
      // 利用createObjectURL，模拟文件下载
      const fileName = '成果图.png';
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        const blobURL = window.URL.createObjectURL(blob)
        const vlink = document.createElement('a');
        vlink.style.display = 'none';
        vlink.href = blobURL;
        vlink.setAttribute('download', fileName);

        if (typeof vlink.download === 'undefined') {
          vlink.setAttribute('target', '_blank');
        }
        document.body.appendChild(vlink);

        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);
        vlink.dispatchEvent(evt);

        document.body.removeChild(vlink);
        window.URL.revokeObjectURL(blobURL);
      }
    });
  };


  //定义handleScroll事件函数
  handleScroll = (e) => {
    //console.log("当前滚动条位置",e,this._container.scrollLeft);
    if (this._container) {
      if (this._container.scrollLeft) {   // 避免报错：scrollLeft is null

        setTimeout(() => {
          this.setState({
            scrollLeft: this._container.scrollLeft
          })
        }, 5)
        console.log(this.state.scrollLeft)

      }

      if (this._container.scrollTop >= 267) {  //if语句判断window页面Y方向的位移是否大于或者等于导航栏的height像素值
        if (!this.state.isFixed) {
          this.setState({
            isFixed: true,
          })
        }
        //console.log("超过265，固定div");
      } else {
        if (this.state.isFixed) {
          this.setState({
            isFixed: false
          })
        }

        //console.log("未超过265，取消固定div")    
      }

    }
  }

  // 点击置顶图标回到顶部，并且给reducer传递一个标记，作用：清除当前选中的所有曲线
  handleReturnTop = () => {
    let pos = this._container.scrollTop;    // 当前页面相对于窗口显示区左上角的Y位置  window.pageYOffset
    this.props.isCancleSelected(!this.props.cancelSelected);   // 标记：触发让选中的曲线都取消选中
    if (pos > 0) {
      this._container.scrollTo(0, 0);  // 窗口目标滚动坐标(x,y)    window
      setTimeout(() => {
        this.handlesaveDocPic();
      }, 300)
    } else if (pos === 0) {
      setTimeout(() => {
        this.handlesaveDocPic();
      }, 300)
    }
  }

  // 视频深度同步的滚动条处理
  handleRemoveAuto = (n) => {
    this.pageYOffset = window.pageYOffset;    // 当前页面相对于窗口显示区左上角的Y位置
    if (n < 3) {
      this._container.scrollTo(0, 265);  // 窗口目标滚动坐标(x,y)
    } else {
      const moveCount = (n - 3) * 2 * this.props.chartZoom + 280;
      console.log(moveCount)
      this._container.scrollTo(0, moveCount);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.docData.doc_id && nextProps.docData.doc_id != this.props.docData.doc_id) {
      console.log("shujuchuli", nextProps, this.props)
      if (nextProps.docData.doc_type === "纯数据文件") {
        this.fileData = nextProps.docData;
        this.setState({
          open_angle: this.fileData.open_angle,
          start_depth: this.fileData.start_depth,
          end_depth: this.fileData.end_depth,
          open_position: this.fileData.open_position,
          declination: this.fileData.declination,
          prospect_line_position: this.fileData.prospect_line_position,

          open_angle_1: this.fileData.open_angle,
          start_depth_1: this.fileData.start_depth,
          end_depth_1: this.fileData.end_depth,
          open_position_1: this.fileData.open_position,
          declination_1: this.fileData.declination,
          prospect_line_position_1: this.fileData.prospect_line_position,
        })
      } else if (nextProps.docData.doc_type === "绘图文件") {
        this.fileData = nextProps.docData.docData;
        this.setState({
          open_angle: this.fileData.open_angle,
          start_depth: this.fileData.start_depth,
          end_depth: this.fileData.end_depth,
          open_position: this.fileData.open_position,
          declination: this.fileData.declination,
          prospect_line_position: this.fileData.prospect_line_position,

          open_angle_1: this.fileData.open_angle,
          start_depth_1: this.fileData.start_depth,
          end_depth_1: this.fileData.end_depth,
          open_position_1: this.fileData.open_position,
          declination_1: this.fileData.declination,
          prospect_line_position_1: this.fileData.prospect_line_position,
        })
      }
    }
  }


  //在componentDidMount生命周期中添加window的handleScroll滑动监听事件
  componentDidMount() {
    // window.addEventListener('scroll', this.handleScroll);
  }
  componentWillMount() {
    document.querySelector('body').style.overflow = 'hidden';
  }

  componentWillUnmount() {    // 换页的时候会被调用
    //console.log("即将被卸载！");
    removeDocDataList();  // 清空 内存中的文件
    removeDepthData();  // 清空 内存中的 初始深度
    this.props.initDaosDataList([]);  // 清空 reducer中的 模板数据
    this.props.initdocData({});  // 清空 reducer中的 文件
    this.props.initmbData([]);   // 清空 reducer中的 模板
    // window.removeEventListener('scroll', this.HandleScroll); // 移除监听
    document.querySelector('body').style.overflow = 'auto';
  }


  render() {
    const fileData = this.fileData;
    const { showHeaderState } = this.state
    console.log(this.props.daosDataList)
    return (
      <LocaleProvider locale={zh_CN} >
        <div className='data-process-wrapper'>
          <div className='data-process-aside' >
            <div class="sideContent">
              <Tabs defaultActiveKey="2" className="tabs" centered type="card" tabBarGutter={0} size='small'>
                <TabPane tab="配置" key="2" style={{ color: "white" }}>
                  <GlobalDataConfig handleReturnTop={this.handleReturnTop} />
                </TabPane>
                <TabPane tab="处理" key="3">
                  <DataConfig handleRemoveAuto={(n) => this.handleRemoveAuto(n)} />
                </TabPane>
                <TabPane tab="管理" key="4">
                  <MbMgt />
                </TabPane>
              </Tabs>
            </div>
          </div>

          <div className='content-wrapper'
            ref={c => this._container = c}
          // onScrollCapture={this.handleScroll}
          >
            <div className='data-process-content' >
              {fileData ?
                <div className="data-process-content-header">
                  <div className="show-title">
                    <span>测井解释成果图</span>
                    <img src={downIcon} alt="" onClick={() => this.setState({ showHeaderState: !showHeaderState })} style={{ transform: showHeaderState ? 'rotate(0deg)' : 'rotate(-180deg)', transition: 'transform 0.24s', marginLeft: 20, cursor: 'pointer' }}></img>
                  </div>
                  {
                    showHeaderState ? <div className="show-header">
                      <Row>
                        <Col span={6}>
                          <label className="w3">钻孔号：</label>
                          <Input className="show-input" value={fileData.drill_id} readonly />   {/*onChange={(e) => this.handleOnChange(e,"钻孔号")}*/}
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w4">仪器型号：</label>
                          <Input className="show-input" defaultValue={fileData.measuring_tool} onChange={(e) => this.handleOnChange(e, "仪器型号")} />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w2">地点：</label>
                          <Input className="show-input show-input-long" defaultValue={fileData.measuring_address} onChange={(e) => this.handleOnChange(e, "地点")} />
                        </Col>
                        <Col span={6}>
                          <label className="w7">测量深度(米)：</label>
                          <Input className="show-input" value={fileData.measuring_depth} readonly /> {/*onChange={(e) => this.handleOnChange1(e,"测量深度")}*/}
                        </Col>
                      </Row>
                      <Row>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w4">探管型号：</label>
                          <Input className="show-input" defaultValue={fileData.ground_tube_type} onChange={(e) => this.handleOnChange(e, "探管型号")} />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w4">测量时间：</label>
                          <DatePicker className="show-input show-input-long" suffixIcon={<div></div>} allowClear={false} defaultValue={moment(fileData.measuring_time, dateFormat)} format={dateFormat} onChange={(e, dateString) => this.handleOnChange2(e, dateString, "测量时间")} />
                        </Col>
                        <Col span={6}>
                          <label className="w7">开孔倾角(度)：</label>
                          <Input className="show-input" defaultValue={fileData.open_angle}
                            onChange={(e) => this.handleOnChange1(e, "开孔倾角")}
                            //onPressEnter={()=> this.handleOnPressEnter()}
                            value={this.state.open_angle_1}
                          />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w4">测井方向：</label>
                          <Input className="show-input" defaultValue={fileData.logging_direction} onChange={(e) => this.handleOnChange(e, "测量方向")} />
                        </Col>
                      </Row>
                      <Row>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w3">测量员：</label>
                          <Input className="show-input show-input-long" defaultValue={fileData.operator} onChange={(e) => this.handleOnChange(e, "测量员")} />
                        </Col>
                        <Col span={6}>
                          <label className="w7">开孔方位(度)：</label>
                          <Input className="show-input" defaultValue={fileData.open_position}
                            onChange={(e) => this.handleOnChange1(e, "开孔方位")}
                            value={this.state.open_position_1}
                          />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w7">起始深度(米)：</label>
                          <InputNumber className="show-input" defaultValue={fileData.start_depth}
                            onChange={(e) => this.handleOnChange1(e, "起始深度")}
                            onPressEnter={(e) => this.handleOnPressEnter(e)}
                            value={this.state.start_depth_1}
                          />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w4">处理时间：</label>
                          <DatePicker className="show-input show-input-long" suffixIcon={<div></div>} allowClear={false} defaultValue={moment(fileData.handle_time, dateFormat)} format={dateFormat} onChange={(e, dateString) => this.handleOnChange2(e, dateString, "处理时间")} />
                        </Col>
                      </Row>
                      <Row>
                        <Col span={6}>
                          <label className="w6">磁偏角(度)：</label>
                          <InputNumber className="show-input" defaultValue={fileData.declination}
                            onChange={(e) => this.handleOnChange1(e, "磁偏角")}
                            //onPressEnter={()=> this.handleOnPressEnter()}
                            value={this.state.declination_1}
                          />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w7">终止深度(米)：</label>
                          <InputNumber className="show-input" defaultValue={fileData.end_depth}
                            onChange={(e) => this.handleOnChange1(e, "终止深度")}
                            onPressEnter={() => this.handleOnPressEnter()}
                            value={this.state.end_depth_1}
                          />
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w3">处理员：</label>
                          <Input className="show-input show-input-long" defaultValue={fileData.handle_person} onChange={(e) => this.handleOnChange(e, "处理员")} />
                        </Col>
                        <Col span={6}>
                          <label className="w8">勘探线方位(度)：</label>
                          <Input className="show-input" defaultValue={fileData.prospect_line_position}
                            onChange={(e) => this.handleOnChange1(e, "勘探线方位")}
                            onPressEnter={() => this.handleOnPressEnter()}
                            value={this.state.prospect_line_position_1}
                          />
                        </Col>
                      </Row>
                      <Row>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w8">采样间隔(米)：</label>
                          <Input className="show-input" value={fileData.sample_interval} readonly />    {/*onChange={(e) => this.handleOnChange1(e,"采样间隔")}*/}
                        </Col>
                        {/* <Col span={2}></Col> */}
                        <Col span={6}>
                          <label className="w2">单位：</label>
                          <Input className="show-input show-input-long" defaultValue={fileData.company} onChange={(e) => this.handleOnChange(e, "单位")} />
                        </Col>
                      </Row>
                    </div> : null
                  }

                </div>
                : null
              }
              <DaoDemo daosDataList={this.props.daosDataList} isFixed={this.state.isFixed} scrollLeft={this.state.scrollLeft} />
            </div>
          </div>
        </div>

      </LocaleProvider>
    )
  }
}

export default connect(
  state => ({
    docData: state.docData, daosDataList: state.daosDataList, mbData: state.mbData,
    cancelSelected: state.cancelSelected, chartZoom: state.gridConfig.chartZoom
  }),
  { editDataDocHeaderInfo, initDaosDataList, initdocData, initmbData, isCancleSelected, setDocInReducer, replaceNewCurves, setEditDepthData }
)(DataProcess);